package com.ocom.aiotweb.service.impl;

import com.alibaba.fastjson.JSON;
import com.ocom.aiotweb.feignclient.AiotClientService;
import com.ocom.aiotweb.service.AccessDeviceService;
import com.ocom.aiotweb.vo.accessdevice.DeleteVo;
import com.ocom.aiotweb.vo.accessdevice.OnShowVo;
import com.ocom.aiotweb.vo.accessdevice.UpgradeVo;
import com.ocom.common.constant.MapKey;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static cn.hutool.poi.excel.cell.CellUtil.getCellValue;

@Slf4j
@Service
public class AccessDeviceServiceImpl implements AccessDeviceService {
    private final Logger log = LoggerFactory.getLogger(AccessDeviceServiceImpl.class);

    @Autowired
    private AiotClientService aiotClientService;

    // 门禁设备列表（AccessDevice/onShow）
    @Override
    public Result AccessDeviceOnShow(OnShowVo onShowVo) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_comId(),onShowVo.getComId());
        map.put(mapKey.getKey_deviceNo(),onShowVo.getDeviceNo());
        map.put(mapKey.getKey_status(),onShowVo.getStatus());
        map.put(mapKey.getKey_deviceType(),onShowVo.getDeviceType());
        map.put(mapKey.getKey_deviceVerType(),onShowVo.getDeviceVerType());
        map.put(mapKey.getKey_appVer(),onShowVo.getAppVer());
        map.put(mapKey.getKey_page(),onShowVo.getPage());
        map.put(mapKey.getKey_size(),onShowVo.getSize());
        return aiotClientService.AccessDeviceGetDeviceInfo(map);
    }

    // 门禁设备新增（AccessDevice/add）
    @Override
    public Result AccessDeviceAdd(String saasNo,Long comId,Long agentId,Long commMode,Integer deviceType,Integer deviceVerType, MultipartFile file) {

        //        1、用HSSFWorkbook打开或者创建“Excel文件对象”
        //        2、用HSSFWorkbook对象返回或者创建Sheet对象
        //        3、用Sheet对象返回行对象，用行对象得到Cell对象
        //        4、对Cell对象读写。
        //获得文件名
        Workbook workbook = null ;
        String fileName = file.getOriginalFilename();
        if(fileName.endsWith("xls")){
            //2003
            try {
                workbook = new HSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else if(fileName.endsWith("xlsx")){
            //2007
            try {
                workbook = new XSSFWorkbook(file.getInputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            try {
                throw new Exception("文件不是Excel文件");
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        Sheet sheet = workbook.getSheetAt(0);
        int rows = sheet.getLastRowNum();// 指的行数，一共有多少行+
        if(rows==0){
            try {
                throw new Exception("请填写数据");
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
        Integer sussCount = 0;
        Integer errCount = 0;
        ArrayList<String> list = new ArrayList<>();
        for (int i = 1; i < rows+1; i++) {
            Map<String, Object> map = new HashMap<>();
            MapKey mapKey = new MapKey();
            map.put(mapKey.getKey_pComId(),comId);
            map.put(mapKey.getKey_pAgentId(),agentId);
            map.put(mapKey.getKey_pSaasNo(),saasNo);
            map.put(mapKey.getKey_commMode(),commMode);
            map.put(mapKey.getKey_deviceType(),deviceType);
            map.put(mapKey.getKey_deviceVerType(),deviceVerType);
            // 读取左端单元格
            Row row = sheet.getRow(i);
            // 行不为空
            String deviceNo = null;
            if (row != null) {

                // **读取cell**
                //设备编号
                deviceNo = JSON.toJSONString(getCellValue(row.getCell(0))).replace("\"","");
                map.put(mapKey.getKey_deviceNo(),deviceNo);
            }
            System.out.println(map);
            try {
                Result result = aiotClientService.AccessDeviceAddDeviceInfo(map);
                if(result.getCode()==200){
                    sussCount++;
                }else {
                    list.add(deviceNo);
                    errCount++;
                }

            }catch (Exception exception){
                log.error(exception.getMessage());
            }
        }
        Map<String,Object> map = new HashMap<>();
        map.put("errDeviceNos",list);
        map.put("errCount",errCount);
        map.put("sussCount",sussCount);
        return ResultUtil.success(map);
    }

    // 门禁设备删除（AccessDevice/delete）
    @Override
    public Result AccessDeviceDelete(DeleteVo deleteVo) {
        String[] deviceNos = deleteVo.getDeviceNo().split(",");
        for (String deviceNo: deviceNos) {
            Map<String,String> stringMap =new HashMap<>();
            stringMap.put("deviceNo",deviceNo);
            try {
                Result result = aiotClientService.AccessDeviceDeleteDeviceInfo(deviceNo,deleteVo.getForce());
                if(result.getCode()!=200){
                    return result;
                }
            }catch (Exception exception){
                log.error("执行门禁设备删除操作失败："+exception.getMessage());
                return ResultUtil.error(ResultEnum.Err_3016,"执行门禁设备删除操作失败");
            }

        }
        return ResultUtil.success();
    }

    // 门禁升级版本列表（AccessDevice/upgradeList）
    @Override
    public Result AccessDeviceUpgradeList(String appVer, Integer deviceType) {
        Map<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_apkType(),deviceType);
        map.put(mapKey.getKey_oldAppVer(),appVer);
        map.put(mapKey.getKey_page(),0);
        map.put(mapKey.getKey_size(),0);
        return aiotClientService.AccessDeviceGetDeviceVerInfo(map);
    }

    // 消费设备升级（ConsumeDevice/upgrade）
    @Override
    public Result AccessDeviceUpgrade(UpgradeVo upgradeVo) {
        String[] deviceNos = upgradeVo.getDeviceNo().split(",");

        for (String deviceNo:deviceNos) {
            Map<String, Object> map = new HashMap<>();
            MapKey mapKey = new MapKey();
            map.put(mapKey.getKey_deviceNo(),deviceNo);
            map.put(mapKey.getKey_appVerTab(),upgradeVo.getUpgradeVer());
            try {
                Result result = aiotClientService.AccessDeviceUpdateDeviceInfo(map);
                if(result.getCode()!=200){
                    return ResultUtil.error(result.getCode());
                }
            }catch (Exception exception){
                exception.printStackTrace();
            }

        }
        return ResultUtil.success();
    }




}
